package com.nnxy.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.nnxy.service.EmpService;
import com.nnxy.mapper.EmpExprMapper;
import com.nnxy.mapper.EmpMapper;
import com.nnxy.pojo.Emp;
import com.nnxy.pojo.EmpExpr;
import com.nnxy.pojo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;


@Service
public class EmpServiceImpl implements EmpService {
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private EmpExprMapper empExprMapper;


    @Override
    public PageResult<Emp> findByPage(Integer page, Integer pageSize, String name, Integer gender, LocalDate begin, LocalDate end) {
        //1.设置PageHelper的分页参数，查询第几页，每页多少条数据
        PageHelper.startPage(page,pageSize);

        //2.调用mapper查询数据返回PageHelper的Page对象
        Page<Emp> pageObj = empMapper.findByPage(name, gender, begin, end);

        //3.获取总条数和当前页数据列表
        long total = pageObj.getTotal();//本质原理：select count(*) from 表 where 条件
        List<Emp> rows = pageObj.getResult();//本质原理：select * from 表 where 条件 limit ?,?

        //4.封装PageResult对象，返回数据
        return new PageResult(rows,total);
    }


    @Override
    public void add(Emp emp) {
        //1.补全员工数据
        emp.setPassword("123456");
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());

        //2.调用empMapper插入员工数据
        empMapper.insert(emp);//插入后 emp.getId()有值

        //3.判断员工是否有工作经历.
        if (emp.getExprList() == null || emp.getExprList().isEmpty()) return;

        //4.工作经历数据补全（emp_id）
        for (EmpExpr expr : emp.getExprList()) {
            expr.setEmpId(emp.getId());
        }

        //5.调用empExprMapper批量插入工作经历数据
        empExprMapper.batchInsert(emp.getExprList());

    }


@Override
@Transactional
public void batchDelete(List<Integer> ids) {
    // 删除员工
    empExprMapper.batchDeleteByEmpIds(ids);
    empMapper.batchDeleteByIds(ids);
    // 删除员工对应的员工expr

}

    @Override
    public Emp findById(Integer id) {
        Emp emp = empMapper.findById(id);
        emp.setExprList(empExprMapper.findById(emp.getId()));
        return emp;
    }

    @Override
    public void modify(Emp emp) {
        emp.setUpdateTime(LocalDateTime.now());
        empMapper.update(emp);

        List<EmpExpr> exprList = emp.getExprList();
        if (exprList != null && !exprList.isEmpty()) {
            ArrayList<Integer> ids = new ArrayList<>();
            ids.add(emp.getId());

            empExprMapper.batchDeleteByEmpIds(ids);

            for (EmpExpr expr : exprList) {
                expr.setEmpId(emp.getId());
            }

            empExprMapper.batchInsert(exprList);
        }

    }
}